import { sys } from "cc"
import BaseSingleClass from "./base/BaseSingleClass"
import GlobalVar from "./GlobalVar";
/**
 * JSWebView与Android/iOS原生交互
 */
export default class JSWebView extends BaseSingleClass{
 
	private funs: {} = {};//map

	//private host = "https://app2.fenzhidao.com/"

	public init():Promise<any>{
		return new Promise<any>((resolve,reject)=>{
			console.log('JSWebView init');
			//console.log(window.location.search);
			//const urlParams = new URLSearchParams(window.location.search);
			// @ts-ignore
			window.callJS = (args:string) => {
				console.log('callJS:'+args)
				let obj = JSON.parse(args);//字符串转json
				let func = obj["func"];//方法名
				let params = obj["params"];//参数
				if (params == null) {
					this.funs[func]();//从map里查找调用
				} else {
					this.funs[func](params);//从map里查找调用
				}
			};
			//延迟执行getToken，如果5秒内Android端没有执行getToken，则直接调用getToken
			const timeout=setTimeout(() => {
				console.log('超过5秒，自动执行getToken')
				//this.funs['getToken']()
				reject()
			}, 1000);
			//map预注册
			this.funs = {
				quit: () => {
					// alert("退出");
				},
				test: (params) => {
					alert(JSON.stringify(params));
				},
				getToken: (params) => {
					//取消延迟执行
					clearTimeout(timeout)
					//this.token = params?.accessToken;
					//this.host = params?.host;
					console.log(params,"getToken");
					resolve(params)
					
					//APIHelper.getInstance().init(params?.accessToken,params?.host)
					//获取题目数据
					/*APIHelper.getInstance().getTopicList({
						gradeId:urlParams.get('gradeId')||'3c954db7449a51c0ea754cb38d6c2169',
						subjectId:urlParams.get('subjectId')||'80bf5d279ae448fecb889d9073b11d08',
						volumeId:urlParams.get('volumeId')||'2ba21d230e76bb3d4abf454261c75060'
					}).then(res=>{
						GlobalVar.topicList=res
						GlobalVar.countDownTime=res.perTime
						if(GlobalVar.gameState==GameState.load)director.loadScene('Game')
					}).catch((err)=>{
						console.error(err)
					})*/
					//获取用户信息
					/*APIHelper.getInstance().getUserInfo().then(res=>{
						console.log(res)
						GlobalVar.user=res
						director.emit(GameEvent.FLUSH_USER)
					}).catch((err)=>{
						console.error(err)
					})*/
				},
				getSafearea: (params) => {
					console.log(params);
					GlobalVar.getInstance().flowingSeaScreenHeight=params.safearea;
					if (params.safearea > 30) {
						//this.TopMargin = params.safearea - 20;
						// EventManager.getInstance().emit(GEventEnum.GameArea);
					}
					//console.log("TopMargin", this.TopMargin);
				},
				update(){
					//UIMgr.instance.close_all();
					//ListenMgr.instance.emit("updateState");
				},
				edenReloadUserInfo(){
					//UIMgr.instance.close_all();
					//ListenMgr.instance.emit("updateState");
				},
				KeyboardEventChange: () => {
					// EventManager.getInstance().emit(GEventEnum.KeyboardEventChange);
				},
			}
		})
	}

	//本方法兼容安卓与iOS
	private callMobile(handlerInterface, handlerMethod, parameters) {
		//handlerInterface由iOS addScriptMessageHandler与andorid addJavascriptInterface 代码注入而来。
		var dic = { 'func': handlerMethod, 'params': parameters };

		// if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)){
			
		if (sys.os == sys.OS.IOS) {
			// @ts-ignore
			window.webkit.messageHandlers[handlerInterface].postMessage(dic);
			// window.webkit.messageHandlers.native.postMessage({'func':'getToken'});
		} else {
			// console.log(window.android[handlerInterface])
			console.log(JSON.stringify(dic));

			//安卓传输不了js json对象
			// @ts-ignore
			// window[handlerInterface][handlerMethod](JSON.stringify(parameters));
			// window[handlerInterface].postMessage(dic);
			// @ts-ignore
			window.android[handlerInterface](JSON.stringify(dic));
		}
	}
	public callMobileNative(handlerMethod, parameters) {
		if (sys.os == sys.OS.ANDROID || sys.os == sys.OS.IOS) {
			if (handlerMethod != null && handlerMethod != "") {
				this.callMobile("callNative", handlerMethod, parameters);
			}
		}
	}



	






}


